<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: CreatePage.php 362 2010-02-03 08:41:11Z steen.rabol@gmail.com $
 *
 */

Prado::using('Application.Common.Data.PortalPagecontentRecord');
Prado::using('Application.Common.Data.PortalPageRecord');
Prado::using('Application.Common.Data.PortalSiteMenuRecord');
Prado::using('Application.Common.Data.PortalSiteMenuItemRecord');
Prado::using('Application.Common.Data.PortalRoleRecord');

class CreatePage extends PortalSystemPage
{
	public function onInit($param)
	{
		parent::onInit($param);

		if(!$this->User)
		{
			$this->reportError(1,"You need to be logged in to use this page");
		}

		if($this->User->RoleId != $this->Application->Parameters['AdminRole'])
		{
			$this->reportError(1,"You need to have admin role to access this page: '" . $this->Service->RequestedPagePath . "'");
		}
	}

	public function onLoad($param)
	{
		parent::onLoad($param);

		$this->Title = $this->Application->Parameters['SiteTitle'] . " - " . Prado::localize("Create page");

		if(!$this->IsPostBack)
		{
			$this->PagePath->DataSource	= $this->DataAccess->createCommand("select * from tblpagepath")->query();
			$this->PagePath->dataBind();

			foreach(PortalUtil::getAvailablePortalLayouts() as $l)
			{

				$pl[] = array("name" => $l['name'], "id" => $l['id']);
			}

			$this->PageLayout->DataSource 		= $pl;
			$this->PageLayout->DataBind();

			$this->Active->Checked	= true;

			// Menu
			$this->SiteMenu->DataSource	=  $this->DataAccess->createCommand("select id,name from tblsitemenu where active=1")->query();
			$this->SiteMenu->dataBind();

			$this->MenuRole->DataSource	= $this->getRoles();
			$this->MenuRole->dataBind();

		}
	}

	public function saveButtonClicked($sender,$param)
	{
		if($this->IsValid)
		{
			// Insert into DB
			$pRecord				= new PortalPageRecord();
			$pRecord->displayname	= $this->DisplayName->Text;
			$pRecord->created		= time();
			$pRecord->modified		= $pRecord->created;
			$pRecord->layoutname	= $this->PageLayout->getSelectedValue();
			$pRecord->active		= TPropertyValue::ensureInteger($this->Active->Checked);
			$pRecord->createdby		= $this->User->Id;

			if($this->PagePath->SelectedValue != "" && $this->PagePath->SelectedValue != "0")
			{
				$pRecord->path		= $this->PagePath->SelectedValue;
				$pRecord->name		= $this->getPageName($pRecord->path);
				$pRecord->fullpath	= $this->PagePath->SelectedValue . '.' . $pRecord->name;
				$newPath			= 'Application.Pages.' . $pRecord->path;
			}
			else
			{
				$pRecord->name		= $this->getPageName();
				$pRecord->fullpath	= $pRecord->name;
				$newPath			= 'Application.Pages';
			}

			$pRecord->metakeywords		= $this->tbMetaKeywords->Text;
			$pRecord->metadescription	= $this->tbMetaDescription->Text;

			$pRecord->save();

			$fullNewPath	= Prado::getPathOfNamespace($newPath) . "/";
			$npname			= $pRecord->name;
			$npphpname		= str_replace("\\","/", $fullNewPath . "/" . $npname . ".php");
			$nppagename		= str_replace("\\","/", $fullNewPath . "/" . $npname . ".page");

			$phpcontent 	= "<?php\r\n// Autogenerated file - DON'T modify!!!\r\nclass $npname extends PortalPage\r\n{\r\n";
			$phpcontent 	.= "}\r\n?>";
			file_put_contents($npphpname,$phpcontent);

			$pagecontent	= "<com:TContent Id=\"Main\" />";
			file_put_contents($nppagename,$pagecontent);

			// Add to menu ?
			if($this->SiteMenu->SelectedValue != "" && $this->SiteMenu->SelectedValue != 0)
			{
				$smi					= new PortalSiteMenuItemRecord();
				$smi->smid				= TPropertyValue::ensureInteger($this->SiteMenu->SelectedValue);
				$smi->title				= $pRecord->displayname;
				$smi->page				= $pRecord->fullpath;
				$smi->img				=  '';
				$smi->active			= TPropertyValue::ensureInteger($this->MenuActive->Checked);
				$smi->role				= TPropertyValue::ensureInteger($this->MenuRole->SelectedValue);
				$smi->target			= '_self';
				$smi->isbreak			= 0;
				$smi->displayorder		= 999;
				$smi->needlogin			= TPropertyValue::ensureInteger($this->MenucbNeedLogin->Checked);
				$smi->showafterlogin	= TPropertyValue::ensureInteger($this->MenucbShowAfterLogin->Checked);
				$smi->save();

				$this->RenumDisplayOrder($smi->smid, 0);
			}
			$this->gotoPage($pRecord->fullpath,array("PageMode" => 1));
		}
	}

	public function validateFileName($sender,$param)
	{
		$npname		= $param->Value;
		if($this->PagePath->SelectedValue != "" && $this->PagePath->SelectedValue != "0")
		{
			$newPath		= 'Application.Pages.' . $npname;
		}
		else
		{
			$newPath		= 'Application.Pages';
		}

		$fullNewPath	= Prado::getPathOfNamespace($newPath) . "/";

		$npphpname	= str_replace("\\","/", $fullNewPath . "/" . $npname . ".php");
		$nppagename	= str_replace("\\","/", $fullNewPath . "/" . $npname . ".page");

		if(file_exists($npphpname) || file_exists($nppagename))
		{
			$param->IsValid = false;
		}
		else
		{
			$param->IsValid = true;
		}
	}

	public function validateFirstLetter($sender,$param)
	{
		if(is_numeric($param->Value[0]))
		{
			$param->IsValid	= false;
		}
	}

	public function getPageName($path = null)
	{
		$pagename	= 'Page' . PortalUtil::GenId("pages_seq");

		// Check if the file exists
		$npPath		= 'Application.Pages.' . ($path !== null ? $path : '');
		$npFileName	= PortalUtil::PathName(Prado::getPathOfNamespace($npPath)) . $pagename;
		if(file_exists($npFileName . '.php'))
		{
			return $this->getPageName($path);
		}

		$fullpath	= ($path !== null ? $path . '.' . $pagename : $pagename);

		// Check page name
		if($this->DbConnection->createCommand("select id from tblpages where fullpath='$fullpath'")->queryScalar())
		{
			return $this->getPageName($path);
		}

		return $pagename;
	}

	public function getRoles()
	{
		return PortalRoleRecord::finder()->findAll();
	}

	public function RenumDisplayOrder($p_id, $p_parent, $p_startat = 999.000)
	{
		$newdisplayorder	= $p_startat;
		$sql				= "select * from tblsitemenuitem where smid= " . $p_id. " and parent=" . $p_parent . " order by displayorder";
		$rows				= $this->DataAccess->createCommand($sql)->query();

		if($rows)
		{
			foreach($rows as $row)
			{
				$sql = "update tblsitemenuitem set displayorder=$newdisplayorder where id='" . $row["id"] . "'";
				$this->DataAccess->createCommand($sql)->execute();
				$newdisplayorder++;
			}
		}
	}
}
?>